<?php
/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('LACONICA')) { exit(1); }

/**
 * Table Definition for profile
 */
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';

class image extends Memcached_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'image';                         // table name
    public $id;                                 // int(4)  primary_key not_null
    public $profile_id;
    public $image;
    public $created;    

    /* Static get */
    function staticGet($k,$v=null)
    { return Memcached_DataObject::staticGet('image',$k,$v); }
    
    function getProfile()
    {
        return Profile::staticGet('id', $this->profile_id);
    }
    
    static function filename($id, $extension, $size=null, $extra=null)
    {
        $month = date("Ym").'/';
        $img_location=INSTALLDIR.'/userimage/'.$month;
        if (is_dir($img_location) == false)
            @mkdir($img_location, 0755);
        if ($size) {
            return $month.$id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
        } else {
            return $month.$id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
        }
    }
    
    function delete()
    {
        $filename = $this->image;
        if (parent::delete()) {
            @unlink(image::path($filename));
            @unlink(image::path_thumbnail($filename,32));
        }
    }

    static function saveNew($profile_id, $imagename) {
        

        $profile = Profile::staticGet($profile_id);

        if (!$profile) {
            common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
            return _('Problem saving notice. Unknown user.');
        }

        if (common_config('throttleimage', 'enabled') && !image::checkEditThrottle($profile_id)) {
            common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
            return _('Bạn upload quá nhiều ảnh trong một thời gian ngắn! Bạn hãy thử lại sau.');
        }

        $banned = common_config('profile', 'banned');

        if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
            common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
            return _('You are banned from posting notices on this site.');
        }

        $image = new image();
        $image->profile_id = $profile_id;
       // $blacklist = common_config('public', 'blacklist');
        # Blacklisted are non-false, but not 1, either

        $image->created = common_sql_now();
        $image->image = $imagename;
        
        $id = $image->insert();
        
        if (!$id) {
            common_log_db_error($image, 'INSERT', __FILE__);
            return _('Problem saving image.');
        }

        return $image;
    }
    
    static function checkEditThrottle($profile_id) {
        $profile = Profile::staticGet($profile_id);
        if (!$profile) {
            return false;
        }
        # Get the Nth notice
        $image = $profile->getImages(common_config('throttleimage', 'count') - 1, 1);
        if ($image && $image->fetch()) {
            # If the Nth notice was posted less than timespan seconds ago
            if (time() - strtotime($image->created) <= common_config('throttleimage', 'timespan')) {
                # Then we throttle
                return false;
            }
        }
        # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
        return true;
    }
    
        static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {

        if (common_config('memcached', 'enabled')) {

            # Skip the cache if this is a since, since_id or before_id qry
            if ($since_id > 0 || $before_id > 0 || $since) {
                return image::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
            } else {
                return image::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
            }
        }

        return image::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
    }

    
       static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {

        $needAnd = false;
        $needWhere = true;

        if (preg_match('/\bWHERE\b/i', $qry)) {
            $needWhere = false;
            $needAnd = true;
        }

        if ($since_id > 0) {

            if ($needWhere) {
                $qry .= ' WHERE ';
                $needWhere = false;
            } else {
                $qry .= ' AND ';
            }

            $qry .= ' image.id > ' . $since_id;
        }

        if ($before_id > 0) {

            if ($needWhere) {
                $qry .= ' WHERE ';
                $needWhere = false;
            } else {
                $qry .= ' AND ';
            }

            $qry .= ' image.id < ' . $before_id;
        }

        if ($since) {

            if ($needWhere) {
                $qry .= ' WHERE ';
                $needWhere = false;
            } else {
                $qry .= ' AND ';
            }

            $qry .= ' image.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
        }

        # Allow ORDER override

        if ($order) {
            $qry .= $order;
        } else {
            $qry .= ' ORDER BY image.created DESC, image.id DESC ';
        }

        if (common_config('db','type') == 'pgsql') {
            $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        } else {
            $qry .= ' LIMIT ' . $offset . ', ' . $limit;
        }

        $image = new image();

        $image->query($qry);

        return $image;
    }

    
    static function path($filename)
    {
        return INSTALLDIR . '/userimage/' . $filename;
    }
    
    static function path_thumbnail($filename,$size)
    {
         $filename=image::getThumbnail($filename,$size);
        return INSTALLDIR . '/userimage/' . $filename;
    }
    static function url($filename)
    {
        return common_path('userimage/'.$filename);
    }
    
    static function url_thumbnail($filename,$size)
    {
        $filename=image::getThumbnail($filename,$size);
        return common_path('userimage/'.$filename);
    }
    
    static function getThumbnail($filename,$size=32)
    {
        $string='-'.$size.'-';
        return str_replace('-original-tmp',$string,$filename);
    }
    

}